package cn.ronghuanet.base.interceptors;

import cn.ronghuanet.auth.service.IPermissionService;
import cn.ronghuanet.base.annotation.RonghuaPermission;
import cn.ronghuanet.base.context.LoginContext;
import cn.ronghuanet.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthenticInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            // 没有token
            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
            return  false;
        }
        // map中拿user
        Object o = LoginContext.loginMap.get(token);
        if (Objects.isNull(o)){
            // 错误的token
            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
            return  false;
        }
        // 鉴权~


        HandlerMethod a = (HandlerMethod)handler;
        String simpleName = a.getBeanType().getSimpleName();
        // 获取用户访问的方法
        Method method = a.getMethod();
        // 1. 判断用户所访问的资源是否要权限
        RonghuaPermission annotation = method.getAnnotation(RonghuaPermission.class);
        if (Objects.isNull(annotation)){
//            response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
            // 没有权限注解表示不需要权限所以直接放行
            return  true;
        }
        // 如果需要权限
        // 2. 通过用户 查询 角色 查询 权限
        Employee user = (Employee)o;
        List<String> sns = permissionService.queryUserPermissionByUserId(user.getId());
        // 拼接方法的sn
        String sn = simpleName +":"+ method.getName();
        // 对比权限
        if (!sns.contains(sn)){
            response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
            return  false;
        }

        return true;
    }
}
